using Assets.Scripts.Entities;
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

namespace Assets.Scripts.Controllers
{
    internal class DayController : BaseController<DayController>
    {
        public static int Day { get => _day; private set => _day = value; }
        public float Progress => _passedTime / _dayDurationInSeconds;

        [SerializeField] private UnityEvent DayEnd;
        [SerializeField] private float _dayDurationInSeconds;

        private float _passedTime;
        private bool _isDayEnded;
        private static int _day = 1;

        public void LoadNextDay()
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }

        protected override void Awake()
        {
            base.Awake();

            Day = PlayerPrefs.GetInt("Day", 1);

            // why
            Application.targetFrameRate = 60;
        }

        private void Update()
        {
            if (_isDayEnded)
            {
                return;
            }

            _passedTime += Time.deltaTime;

            if (_passedTime >= _dayDurationInSeconds)
            {
                Day++;
                PlayerPrefs.SetInt("Day", Day);

                _passedTime = _dayDurationInSeconds;
                DayEnd?.Invoke();
                _isDayEnded = true;

                HandleDayEnd();
            }
        }

        private void HandleDayEnd()
        {
            FindObjectOfType<VisitorsController>().Stop();
            var childs = FindObjectsOfType<Child>();
            foreach (var item in childs)
            {
                if (item.CurrentState != Child.State.Leaving)
                {
                    Destroy(item.gameObject);
                }
            }
        }
    }
}
